package hczc.longcai.com.hccrowdfunding.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import hczc.longcai.com.hccrowdfunding.R;
import hczc.longcai.com.hccrowdfunding.activity.beans.LoginInfo;
import hczc.longcai.com.hccrowdfunding.application.BaseApplication;
import hczc.longcai.com.hccrowdfunding.utils.MD5Utils;
import hczc.longcai.com.hccrowdfunding.utils.httputils.HttpPath;
import hczc.longcai.com.hccrowdfunding.utils.httputils.LoadDatas;
import hczc.longcai.com.hccrowdfunding.utils.json.ParseJSON;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity";

    private TextView register;
    private EditText number;
    private EditText passwd;
    private Button button;

    private ScrollView contentView;
    private ProgressBar loadingView;

    private SharedPreferences mSharedPreferences;

    private LoginAsyncTask asyncTask;
    private LoadDatas loadDatas;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mSharedPreferences = BaseApplication.mSharedPreferences;

        loadDatas = new LoadDatas();

        initViews();
    }

    private void initViews() {

        findViewById(R.id.head_back).setOnClickListener(this);
        ((TextView) findViewById(R.id.head_title)).setText("登陆");
        register = ((TextView) findViewById(R.id.head_right_text));
        findViewById(R.id.headbar_background).setBackgroundColor(Color.parseColor("#00000000"));
        register.setVisibility(View.VISIBLE);
        register.setOnClickListener(this);

        contentView = ((ScrollView) findViewById(R.id.login_contentview));
        loadingView = ((ProgressBar) findViewById(R.id.login_loadingview));
        loadingView.setVisibility(View.GONE);

        findViewById(R.id.login_forget_password).setOnClickListener(this);

        initInput();


    }

    /**
     * 初始化输入框及登录按钮
     */

    private void initInput() {
        number = ((EditText) findViewById(R.id.login_input_number_edit));
        passwd = ((EditText) findViewById(R.id.login_input_passwd_edit));
        button = ((Button) findViewById(R.id.login_button));
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.head_back:
                finish();
                break;

            case R.id.head_right_text:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;

            case R.id.login_forget_password:
                startActivity(new Intent(LoginActivity.this, FindPasswdActivity.class));
                break;

            case R.id.login_button:
                InputMethodManager imm =(InputMethodManager)getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(passwd.getWindowToken(), 0);
                loginSuccess();
                break;
        }
    }

    /**
     * 判断是否登录成功
     */

    private void loginSuccess() {
        String c_number = number.getText().toString().trim();
        String c_passwd = passwd.getText().toString().trim();

        boolean empty = isEmpty(c_number, c_passwd);
        if (empty) {
            showProgress(empty);
            asyncTask = new LoginAsyncTask(c_number, c_passwd);
            asyncTask.execute(((Void) null));
        }
    }

    /**
     * 判断输入框是否符合条件
     *
     * @param c_number 电话号码
     * @param c_passwd 密码
     * @return 若符合条件返回true
     */

    private boolean isEmpty(String c_number, String c_passwd) {
        boolean flag = true;
        if (TextUtils.isEmpty(c_number)) {
            Toast.makeText(LoginActivity.this, "手机号码不能为空", Toast.LENGTH_SHORT).show();
            setFocus(number);
            flag = false;
            return flag;
        } else if (c_number.length() != 11) {
            Toast.makeText(LoginActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            number.setText("");
            passwd.setText("");
            setFocus(number);
            flag = false;
            return flag;
        }

        if (TextUtils.isEmpty(c_passwd)) {
            Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
            setFocus(passwd);
            flag = false;
            return flag;
        }

        return flag;
    }

    /**
     * 设置EditText的焦点
     *
     * @param et 要设置的EditText
     */
    private void setFocus(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();
        et.findFocus();
    }

    /**
     * 显示进度条
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            contentView.setVisibility(show ? View.GONE : View.VISIBLE);
            contentView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    contentView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            loadingView.setVisibility(show ? View.VISIBLE : View.GONE);
            loadingView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    loadingView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            loadingView.setVisibility(show ? View.VISIBLE : View.GONE);
            contentView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }



    /**
     * 登陆的异步任务
     */

    public class LoginAsyncTask extends AsyncTask<Void, Void, Boolean> {

        private String c_phone;
        private String c_password;

        private String tips;
        private String uid;

        public LoginAsyncTask(String phone, String password) {

            c_phone = phone;
            c_password = password;
//            Log.d(TAG,"用户名：" + c_phone + ",密码：" + c_password);

        }


        @Override
        protected Boolean doInBackground(Void... params) {
            boolean flag = false;
            try {
                String s = MD5Utils.MD5(c_password);
                String login = HttpPath.getURL_LOGIN(c_phone, s);
//                Log.d(TAG,"*****************"+s+"*********************");
                byte[] datas = loadDatas.getDatas(login);
                String JSON = new String(datas, 0, datas.length);
                LoginInfo info = ParseJSON.parseLogin(JSON);
                String status = info.getStatus();
                tips = info.getTips();
                if ("1".equals(status)) {
                    uid = info.getUid();
                    String url_userinfo = HttpPath.getURL_Userinfo(uid);
                    byte[] userDatas = loadDatas.getDatas(url_userinfo);
                    String userJSON = new String(userDatas, 0, userDatas.length);
                    ParseJSON.parseUser(userJSON);
                    flag = true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


            return flag;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            showProgress(false);
            if (aBoolean) {
                Toast.makeText(LoginActivity.this,tips,Toast.LENGTH_SHORT).show();
                writeShare();
                setResult(1);
                finish();
            } else {
                Toast.makeText(LoginActivity.this, tips, Toast.LENGTH_SHORT).show();
            }
        }

        private void writeShare() {
            SharedPreferences.Editor editor = mSharedPreferences.edit();
            editor.putBoolean("isLogin", true);
            editor.putString("uid",uid);
            editor.commit();
        }

        @Override
        protected void onCancelled() {
            asyncTask = null;
            showProgress(false);
        }
    }
}
